<template>
  <div class="min-h-screen flex">
    <!-- 左侧展示区 -->
    <div class="w-2/5 relative overflow-hidden">
      <div class="absolute inset-0">
        <img
            :src="'https://ai-public.mastergo.com/ai/img_res/a2c7855f1dce453a44dabf9d8a552a67.jpg'"
            class="w-full h-full object-cover object-top"
            alt="Background"
        />
      </div>
      <div class="relative z-10 flex flex-col h-full p-12 text-white">
        <div class="text-4xl font-bold mb-6">智能维保合同管理系统</div>
        <div class="text-xl mb-8">智能维保合同管理系统</div>
        <p class="text-lg opacity-80 leading-relaxed mb-8">
          以科技创新推动教育进步<br />
          让管理更智能，让学习更高效
        </p>
      </div>
    </div>
    <!-- 右侧登录区 -->
    <div class="w-3/5 relative">
      <div class="absolute inset-0">
        <img
            :src="'https://ai-public.mastergo.com/ai/img_res/028430e6f4cfcd05870059185f4fc9f7.jpg'"
            class="w-full h-full object-cover"
            alt="Login Background"
        />
      </div>
      <div class="relative z-10 flex items-center justify-center h-screen">
        <div class="w-full max-w-md backdrop-blur-sm bg-white/80 p-12 rounded-2xl shadow-lg">
          <h1 class="text-3xl font-bold text-gray-800 mb-12">智能维保合同管理系统</h1>
          <form @submit.prevent="handleLogin" class="space-y-6">
            <div class="relative">
              <i class="fas fa-user absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
              <input
                  v-model="loginData.username"
                  type="text"
                  class="w-full pl-12 pr-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none transition-colors text-sm"
                  placeholder="请输入账号"
              />
            </div>
            <div class="relative">
              <i class="fas fa-lock absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
              <input
                  v-model="loginData.password"
                  :type="showPassword ? 'text' : 'password'"
                  class="w-full pl-12 pr-12 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none transition-colors text-sm"
                  placeholder="请输入密码"
              />
              <button
                  type="button"
                  @click="togglePassword"
                  class="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 !rounded-button"
              >
                <i :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
              </button>
            </div>
            <div class="flex space-x-4">
              <div class="relative flex-1">
                <input
                    v-model="captcha"
                    type="text"
                    class="w-full pl-4 pr-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none transition-colors text-sm"
                    placeholder="验证码"
                />
              </div>
              <div
                  class="w-32 h-12 bg-gray-100 rounded-lg flex items-center justify-center cursor-pointer"
                  @click="refreshCaptcha"
              >
                {{ captchaCode }}
              </div>
            </div>
            <div class="flex gap-4 mb-6">

    <span v-for="item in menus" v-bind:key="item.roleName">
      <label class="flex items-center cursor-pointer" v-if="item.roleName!='游客'">
      <input
          type="radio"
          :value="item.roleName"
          v-model="loginData.role"
          class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500"
      />
      <span class="ml-2 text-sm text-gray-600">{{item.roleName}}</span>
    </label>
   </span>
            </div>
            <button
                type="submit"
                :class="{'opacity-75': isLoading}"
                :disabled="isLoading"
                class="w-full py-3 bg-gradient-to-r from-blue-600 to-blue-400 text-white rounded-lg hover:shadow-lg transform hover:scale-[1.02] transition-all duration-300 flex items-center justify-center space-x-2 !rounded-button whitespace-nowrap"
            >
              <i v-if="isLoading" class="fas fa-circle-notch fa-spin"></i>
              <span>{{ isLoading ? '登录中...' : '登录' }}</span>
            </button>
          </form>
          <div v-if="errorMsg" class="mt-4 p-4 bg-red-50 text-red-600 rounded-lg text-sm">
            {{ errorMsg }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, toRefs,defineAsyncComponent,onMounted } from 'vue';
  import { isUsername, isPassword } from '@/utils/validate';
  import { useAuthStore } from '@/stores/auth';
  import { useRouter, useRoute } from 'vue-router';
  import { Session } from '@/utils/storage';
  import type { FormRules } from 'element-plus/es/components/form/src/types';
  import menu from "@/utils/menu";
  import {notify,confirm} from '@/utils/element';
  const Register=defineAsyncComponent(()=>import('@/views/login/register.vue'));
  const authStore = useAuthStore();

  const router = useRouter();
  const route = useRoute();

  const formRef = ref();

  const state = reactive({
    loading: false,
    registerloading:false,
    loginData: {
      username: '',
      password: '',
      role:''
    } as LoginData,
    tableName:''
  });

  const menus = menu.list();

  const { loading, loginData,tableName } = {...toRefs(state)};
  const RegisterRef=ref();
  function  register(tableName:any) {
    RegisterRef.value.open(tableName);
  }

  const username = ref('');
  const password = ref('');
  const captcha = ref('');
  const captchaCode = ref('ABCD');
  const showPassword = ref(false);
  const isLoading = ref(false);
  const errorMsg = ref('');
  const role = ref('student');

  const registerAs = (type: string) => {
    console.log(`Register as ${type}`);
    // 实现注册逻辑
  };
  const togglePassword = () => {
    showPassword.value = !showPassword.value;
  };
  const refreshCaptcha = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let result = '';
    for (let i = 0; i < 4; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    captchaCode.value = result;
  };
  const handleLogin = async () => {
    if (!loginData.value.username || !loginData.value.password || !captcha.value) {
      errorMsg.value = '请填写完整登录信息';
      return;
    }
    if (captcha.value.toUpperCase() !== captchaCode.value) {
      errorMsg.value = '验证码错误';
      refreshCaptcha();
      captcha.value = '';
      return;
    }
    isLoading.value = true;
    errorMsg.value = '';
    try {
      for (let i = 0; i < menus.length; i++) {
        if (menus[i].roleName == loginData.value.role) {
          state.tableName = menus[i].tableName;
        }
      }

      const res = await authStore.userLogin(state.loginData,`${state.tableName}/login`);
      // console.log('submitForm', res);
      // 跳转到来源地址  login?redirect=/home
      Session.set("tableName",state.tableName);
      Session.set("role", state.loginData.role);
      Session.set("adminName", state.loginData.username);
      router.replace({path: <string>route.query?.redirect || '/'});



    } catch (error) {
      errorMsg.value = '登录失败，请稍后重试';
    } finally {
      isLoading.value = false;
    }
  };
</script>
<style scoped>
  .login-form-shadow {
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  }
  input[type="number"]::-webkit-inner-spin-button,
  input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
</style>



